package cn.jdy.framework.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

/**
 * spring mvc 上传文件
 * 
 * @author wuzhiliang
 * 
 */
public class SpringUploadFile {

  // 文件大小常量, 单位kb
  private static long MAX_SIZE = 1024 * 1024 * 200;
  private static String[] allowFiles = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" ,".docx",".mp4",".mov",".p12"};

  /**
   * 上传文件 有待改进及加多文件上传
   * 
   * @param request
   * @param savePath
   * @return
   */
  public static Map<String, String> upload(DefaultMultipartHttpServletRequest request,
      String savePath) {
    Map<String, String> map = new HashMap<String, String>();
    try {
      Iterator<String> fileNames = request.getFileNames();
      String upFileName = "file";
      while(fileNames.hasNext()){
        upFileName = fileNames.next();
      }
      // 获得文件：
      MultipartFile file = request.getFile(upFileName);
      if (file.isEmpty()) {
        map.put("errorInfo", "文件未上传,请选择文件");
      } else if (file.getSize() > MAX_SIZE) {
        map.put("errorInfo", "文件长度不能超过4M");
      } else if (!checkFileType(file.getOriginalFilename(), allowFiles)) {// 文件上传类型错误
        map.put("errorInfo", "文件上传类型不正确");
      } else {
        String originalName = file.getOriginalFilename();
        String fileRoot = "/upload";
        String path = request.getSession().getServletContext().getRealPath("/");
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
        String newfileDir = formater.format(new Date());
        path = new File(path).getParent() + fileRoot + "/" + savePath + "/" + newfileDir;
        String fileName = IDUtil.getID() + getFileExt(originalName);// 根据原生文件后缀名 生成新文件名
        File targetFile = new File(path, fileName);
        if (!targetFile.exists()) {
          targetFile.mkdirs();
        }
        // 保存
        try {
          file.transferTo(targetFile);
        } catch (Exception e) {
          map.put("errorInfo", "文件上传失败");
        }
        map.put("originalName", originalName);
        map.put("newUrl", fileRoot + "/" + savePath + "/" + newfileDir + "/" + fileName);
      }

    } catch (Exception e) {
      map.put("errorInfo", "文件上传失败");
    }
    return map;
  }

  /**
   * 获取文件扩展名
   * 
   * @return string
   */
  private static String getFileExt(String fileName) {
    if (fileName != null && fileName.lastIndexOf(".") > 0)
      return fileName.substring(fileName.lastIndexOf("."));
    else
      return "";
  }

  /**
   * 文件类型判断
   * 
   * @param fileName
   * @return
   */
  private static boolean checkFileType(String fileName, String[] allowFiles) {
    Iterator<String> type = Arrays.asList(allowFiles).iterator();
    while (type.hasNext()) {
      String ext = type.next();
      if (fileName.toLowerCase().endsWith(ext)) {
        return true;
      }
    }
    return false;
  }

  /**
   * 上传文件 有待改进及加多文件上传
   * 
   * @param request
   * @param savePath
   * @return
   */
  public static Map<String, String> uploadFile(DefaultMultipartHttpServletRequest request,
      String savePath, int maxSize, String[] fileType) {
    Map<String, String> map = new HashMap<String, String>();
    try {
      // 获得文件：
      MultipartFile file = request.getFile("file");
      if (file.isEmpty()) {
        map.put("errorInfo", "文件未上传,请选择文件");
      } else if (file.getSize() > maxSize) {
        map.put("errorInfo", "文件太大");
      }
      // else if (!checkFileType(file.getOriginalFilename(),fileType)) {//
      // 文件上传类型错误
      // map.put("errorInfo", "文件上传类型不正确");
      // }
      else {
        String originalName = file.getOriginalFilename();
        String fileRoot = "/upload";
        String path = request.getSession().getServletContext().getRealPath("/");
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
        String newfileDir = "/" + formater.format(new Date());
        path = new File(path).getParent() +  fileRoot + "/" + savePath + "/" + newfileDir;
        String fileName = IDUtil.getID() + getFileExt(originalName);// 根据原生文件后缀名 生成新文件名
        File targetFile = new File(path, fileName);
        if (!targetFile.exists()) {
          targetFile.mkdirs();
        }
        // 保存
        try {
          file.transferTo(targetFile);
        } catch (Exception e) {
          map.put("errorInfo", "文件上传失败");
        }
        map.put("originalName", originalName);
        map.put("newUrl", fileRoot + "/" + savePath + "/" + newfileDir + "/" + fileName);
      }

    } catch (Exception e) {
      map.put("errorInfo", "文件上传失败");
    }
    return map;
  }

  /**
   * 上传单个附件
   */
  public static Map<String, String> uploadFile(MultipartFile file, HttpServletRequest request,
      String savePath) {
    Map<String, String> map = new HashMap<String, String>();
    try {
      if (file.isEmpty()) {
        map.put("errorInfo", "文件未上传,请选择文件");
      } else if (file.getSize() > MAX_SIZE) {
        map.put("errorInfo", "文件长度不能超过4M");
      } else if (!checkFileType(file.getOriginalFilename(), allowFiles)) {// 文件上传类型错误
        map.put("errorInfo", "文件上传类型不正确");
      } else {

        String fileRoot = "/upload";
        String path = request.getSession().getServletContext().getRealPath("/");
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
        String newfileDir = formater.format(new Date());
        path = new File(path).getParent() + fileRoot + "/" + savePath + "/" + newfileDir;
        String originalName = file.getOriginalFilename();
        String fileName = IDUtil.getID() + getFileExt(originalName);// 根据原生文件后缀名 生成新文件名
        File targetFile = new File(path, fileName);
        if (!targetFile.exists()) {
          targetFile.mkdirs();
        }
        byte[] bytes = file.getBytes();
        // 保存
        try {
          file.transferTo(targetFile);
        } catch (Exception e) {
          map.put("errorInfo", "文件上传失败");
        }
        map.put("originalName", originalName);
        map.put("newUrl", fileRoot + "/" + savePath + "/" + newfileDir + "/" + fileName);

      }
    } catch (Exception e) {
      // TODO: handle exception
    }
    return map;
  }

}
